package cn.duli.xianer.controller;


import cn.duli.xianer.pojo.*;
import cn.duli.xianer.service.GoodsService;
import cn.duli.xianer.service.OrdersService;
import cn.duli.xianer.service.ShopcarService;
import cn.duli.xianer.utils.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ShopcarService shopcarService;


    /**
     * 新增订单
     * 订单创建成功，不管用户是否付款，都要将对应的商品下架，相应购物车清空
     * @param orders
     * @return
     */
    @PostMapping("/save")
    @RequiresRoles("business")
    public MyResult save(@RequestBody List<Orders> orders) {
        List<Orders> ordersList = new ArrayList<>();
        String oParentNo = StrUtil.getOrderNo();
        for (int i=0;i<orders.size();i++) {
            // 随机数生成订单编号，用时间精确到秒然后再随机10个数拼接起来
            // 生成订单编号
            orders.get(i).setoOrderNum(StrUtil.getOrderNo());
            // 生成总订单编号
            orders.get(i).setoParentNo(oParentNo);
            // 新增订单项
            int oId = ordersService.save(orders.get(i));
            Orders orderItem = ordersService.findById(oId);
            // 将新增的订单项返回
            ordersList.add(orderItem);
            // 商品下架
            goodsService.shelveById(orders.get(i).getoGid());
            // 根据用户Id和商品id清空对应购物车商品
            shopcarService.deleteByUidAndGid(orders.get(i).getoUid(), orders.get(i).getoGid());
        }
        return new MyResult(200, "新增订单成功",null,ordersList,null,null);
    }


    /**
     * 根据订单表id查询订单详情
     * @param oId
     * @return
     */
    @GetMapping("/findById/{oId}")
    @RequiresRoles("business")
    public MyResult findById(@PathVariable("oId") Integer oId){
        Orders orders = ordersService.findById(oId);
        return new MyResult(200, "根据订单表id查询订单详情",null,null,orders,null);
    }



    /**
     * 根据订单号查询订单
     * @param orderNum
     * @return
     */
    @GetMapping("/findByOrderNum")
    @RequiresRoles("business")
    public MyResult findByOrderNum(@RequestParam("orderNum") String orderNum){
        Orders orders = ordersService.findByOrderNum(orderNum);
        return new MyResult(200, "根据订单表id查询订单详情",null,null,orders,null);
    }

    /**
     * 根据用户id查询订单列表
     * @param uId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/findOrdersByuId")
    @RequiresRoles("business")
    public MyResult findOrdersByuId(@RequestParam("uId") Integer uId,
                                          @RequestParam(defaultValue = "1",required = false) int pageNo,
                                          @RequestParam(defaultValue = "6",required = false) int pageSize ) {
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersService.findOrdersByuId(uId));
        return new MyResult(200, "根据用户id查询订单列表成功",null,null,null,pageInfo);

    }

    /**
     * 根据id删除此订单
     * @param oId
     * @return true 删除成功,false 删除失败
     */
    @GetMapping("/deleteById/{oId}")
    @RequiresRoles("business")
    public boolean deleteById(@PathVariable("oId") Integer oId){
        int temp = ordersService.deleteById(oId);
        return temp==1?true:false;
    }

    /**
     * 根据订单id去发货（更改订单状态为待收货），和更改发货时间
     * @param oId
     * @return true 更改成功,false 更改失败
     */
    @GetMapping("/updateDeliverStatus/{oId}")
    @RequiresRoles("business")
    public boolean updateDeliverStatus(@PathVariable("oId") Integer oId){
        int temp = ordersService.updateDeliverStatus(oId);
        return temp==1?true:false;
    }

    /**
     * 根据订单id确认收货（更改订单状态为交易成功），和更改确认收货时间
     * @param oId
     * @return true 更改成功,false 更改失败
     */
    @GetMapping("/updateConfirmOrder/{oId}")
    @RequiresRoles("business")
    public boolean updateConfirmOrder(@PathVariable("oId") Integer oId){
        int temp = ordersService.updateConfirmOrder(oId);
        return temp==1?true:false;
    }

    /**
     * 根据订单id关闭交易(订单状态为已取消)，将取消的商品上架和购物车重新新增此商品
     * @param oId
     * @return true 更改成功,false 更改失败
     */
    @GetMapping("/updateOrderClose/{oId}")
    @RequiresRoles("business")
    public MyResult updateOrderClose(@PathVariable("oId") Integer oId){
        int temp = ordersService.updateOrderClose(oId);
        if (temp==1) {
            Orders order = ordersService.findById(oId);
            // 取消被下架的商品
            goodsService.cancelShelveById(order.getoGid());
            Goods good = goodsService.findById(order.getoGid());
            Shopcar shopcar = new Shopcar();
            shopcar.setsGid(order.getoGid());
            shopcar.setsUid(order.getoUid());
            shopcar.setsTotal(order.getoTotalAmount());
            shopcar.setsPrice(good.getgPrice());
            shopcar.setsFire(good.getgFire());
            // 新增购物车
            shopcarService.save(shopcar);
            return new MyResult(200, "根据订单id关闭交易成功",null,null,null,null);
        } else {
            return new MyResult(400, "根据订单id关闭交易失败",null,null,null,null);
        }
    }


    /**
     * 根据总订单编号查询相关订单列表
     * @param parentNo
     * @return
     */
    @GetMapping("/findByParentNo/{parentNo}")
    public MyResult findByParentNo(@PathVariable("parentNo") String parentNo){
        List<Orders> ordersList = ordersService.findByParentNo(parentNo);
        return new MyResult(200, "根据总订单编号查询相关订单列表",null,ordersList,null,null);
    }

    /**
     * 根据商品Id查询订单
     * @param gId
     * @return
     */
    @GetMapping("/findByGoodId")
    @RequiresRoles("business")
    public MyResult findByGoodId(@RequestParam("gId") Integer gId){
        Orders orders = ordersService.findByGoodId(gId);
        return new MyResult(200, "根据商品Id查询订单",null,null,orders,null);
    }

    /**
     * 分组查询待付款的订单列表
     * @return
     */
    @GetMapping("/findNotPad")
    @RequiresRoles("business")
    public MyResult findNotPad(@RequestParam("uId") Integer uId){
        List<Orders> ordersList = ordersService.findNotPad(uId);
        return new MyResult(200, "分组查询待付款的订单列表",null,ordersList,null,null);
    }


    /**
     * 分页根据订单状态查询订单列表
     * @return
     */
    @GetMapping("/findByStatusPage")
    @RequiresRoles("business")
    public MyResult findByStatusPage(@RequestParam(defaultValue = "1") int pageNo,
                                    @RequestParam(defaultValue = "6") int pageSize,
                                     @RequestParam("status") String status,
                                     @RequestParam("uId") Integer uId){
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersService.findByStatusPage(status, uId));
        return new MyResult(200, "查询待收货的订单列表",null,null,null,pageInfo);
    }

    /**
     * 根据订单状态查询订单列表
     * @return
     */
    @GetMapping("/findByOrderStatus")
    public MyResult findRefunding(){
        List<Orders> ordersList = ordersService.findByOrderStatus();
        return new MyResult(200, "根据订单状态查询订单列表",null,ordersList,null,null);
    }


    /**
     * 根据订单中商品的发布用户id查询订单列表（我卖出的订单列表）
     * @param uId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/findSellList")
    @RequiresRoles("business")
    public MyResult findSellList(@RequestParam("uId") Integer uId,
                                    @RequestParam(defaultValue = "1",required = false) int pageNo,
                                    @RequestParam(defaultValue = "6",required = false) int pageSize ) {
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersService.findSellList(uId));
        return new MyResult(200, "根据订单中商品的发布用户id查询订单列表（我卖出的订单列表）",null,null,null,pageInfo);
    }

    /**
     * 分页根据订单中商品的发布用户id和订单状态查询订单列表（我卖出的）
     * @param pageNo
     * @param pageSize
     * @param status
     * @param uId
     * @return
     */
    @GetMapping("/findByStatusBySell")
    @RequiresRoles("business")
    public MyResult findByStatusBySell(@RequestParam(defaultValue = "1") int pageNo,
                                     @RequestParam(defaultValue = "6") int pageSize,
                                     @RequestParam("status") String status,
                                     @RequestParam("uId") Integer uId){
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersService.findByStatusBySell(status, uId));
        return new MyResult(200, "分页根据订单中商品的发布用户id和订单状态查询订单列表（我卖出的）",null,null,null,pageInfo);
    }

    /**
     * 根据订单id修改订单状态
     * @param status
     * @param oId
     * @return
     */
    @GetMapping("/updateOrderStatus")
    @RequiresRoles("business")
    public boolean updateOrderStatus(@RequestParam("status") Integer status,
                                     @RequestParam("oId") Integer oId){
        int temp = ordersService.updateOrderStatus(oId, status);
        return temp==1?true:false;
    }

    /**
     * 查询所有订单
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/findAll")
    @RequiresRoles("admin")
    public MyResult findAll(@RequestParam(defaultValue = "1",required = false) int pageNo,
                            @RequestParam(defaultValue = "6",required = false) int pageSize ) {
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersService.findAll());
        return new MyResult(200, "查询所有订单",null,null,null,pageInfo);
    }

    /**
     * 查询交易成功的订单列表
     * @return
     */
    @GetMapping("/findSuccess")
    @RequiresRoles("admin")
    public MyResult findSuccess(){
        List<Orders> ordersList = ordersService.findSuccess();
        return new MyResult(200, "查询交易成功的订单列表",null,ordersList,null,null);
    }
}
